package mysttest.list;

import java.util.Scanner;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/7/23 1:31
 */
public class MyLinkedList{
    // 节点
    class Node {

        int data;
        Node next;
        public Node(){}
        public Node(int data){this.data = data;}
    }

    private Node head; // 头指针

    // 创建一个单链表
    // 1. 头插法
    public void addFirst(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
            return;
        }
        newNode.next = head;
        head = newNode;

    }

    // 2. 尾插法
    public void addLast(int data) {
        Node newNode = new Node(data); // 创建一个新节点
        if (head == null) {
            head = newNode;
            return;
        }
        // 正常的尾插
        Node cur = head;
        while (cur.next != null) {
            cur = cur.next;
        }
        cur.next = newNode;
    }

    // 删除链表中的指定元素
    // 1. 删除一个(删除链表中出现的第一个)
    public boolean removeFirstVal(int val) {
        // 先判断链表是否为空, 如果链表为空就不能删除
        if (isEmpty()) {
            return false;
        }
        // 1. 要删除的元素就是链表头
        if (head.data == val) {
            head = head.next;
            return true;
        }
        // 正常的删除操作
        Node pre = head;
        Node cur = head.next;
        while (cur != null) {
            if (cur.data == val) {
                break;
            }
            cur = cur.next;
            pre = pre.next;
        }
        if (cur != null) {
            pre.next = cur.next;
        }
        return true;
    }


    // 2. 删除所有



    public boolean isEmpty() {
        return head == null;
    }


    // 遍历单链表
    public void display() {
        if (head == null) {
            System.out.println("当前链表为空");
            return;
        }
        Node cur = head;
        while (cur != null) {
            System.out.print(cur.data + " ");
            cur = cur.next;
        }
        System.out.println();
    }

    // 用于测试
    public static void main(String[] args) {
        MyLinkedList myLinkedList = new MyLinkedList();
        myLinkedList.addLast(1);
        myLinkedList.addLast(2);
        myLinkedList.addLast(3);
        myLinkedList.addLast(4);
        myLinkedList.addLast(5);
        myLinkedList.removeFirstVal(5);
        myLinkedList.display();
        myLinkedList.removeFirstVal(1);
        myLinkedList.display();
        myLinkedList.removeFirstVal(3);
        myLinkedList.display();
    }

}